package com.amado.course40Reflect;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

import sun.misc.ProxyGenerator;

/**
 * Created by Administrator on 2018/1/7.
 */
public class S06ProxyClass {
    public static void main(String[] args) {
        GoodsService userService = new GoodsServiceImpl();
        GoodsService userProxy = (GoodsService) Proxy.newProxyInstance(S06ProxyClass.class.getClassLoader(), new Class[]{GoodsService.class}, (Object proxy, Method method, Object[] argss) -> {
            System.out.println("do being");
            method.invoke(userService, argss);
            System.out.println("do end");
            System.out.println(proxy.getClass().getName());
            return null;
        });
        userProxy.getUserName(1);
        buildClass();
    }

    public static void buildClass() {
        byte[] bytes = ProxyGenerator.generateProxyClass("GoodsService$Proxy", new Class[]{GoodsService.class});
        OutputStream outputStream = null;

        String dir = System.getProperty("user.dir");
        try {
            File direcotry= new File(dir + "/target/");
            if(!direcotry.exists()){
                direcotry.mkdir();
            }
            File file =new File(dir + "/target/GoodsService$Proxy.class");
            if(!file.exists()){
                file.createNewFile();
            }
            System.out.println(file.getPath());
            outputStream = new FileOutputStream(file);
            outputStream.write(bytes);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

interface GoodsService {
	String getUserName(long id);
	List<String> list();
	boolean delete(long id);
}

class GoodsServiceImpl implements GoodsService {
	
    @Override
	public List<String> list() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean delete(long id) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
    public String getUserName(long id) {
        System.out.println("do..........");
        return "name " + id;
    }
}
